package service;

import entity.Player;
import entity.User;
import game.Z5CGame;

import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import java.util.concurrent.ConcurrentHashMap;

public class PlayerServiceImp implements PlayerService {

    private static PlayerServiceImp playerServiceImp = new PlayerServiceImp();
    public static PlayerServiceImp getPlayerServiceImp() {
        return playerServiceImp;
    }

    private ConcurrentHashMap<Session, Player> players;
    private ConcurrentHashMap<HttpSession, Player> playersHttpIndex;

    private PlayerServiceImp() {
        players = new ConcurrentHashMap<>();
        playersHttpIndex = new ConcurrentHashMap<>();
    }

    @Override
    public final Player regist(HttpSession httpSession, Session s, User userInfo) {
        if(s == null) return null;
        Player p = getBySession(s);
        if(p == null) {
            p = new Player(httpSession, s, Z5CGame.Camp.none, userInfo);
            players.put(s, p);
            playersHttpIndex.put(httpSession, p);
        }
        return p;
    }

    @Override
    public final Player getBySession(Session s) { return players.get(s); }

    @Override
    public final Player getBySession(HttpSession s) { return playersHttpIndex.get(s); }

    @Override
    public final void unregist(Session s) {
        Player p = players.remove(s);
        playersHttpIndex.remove(p.getHttpSession());
    }
}
